package net.woggle.shackbrowseapi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class LoginDownload {
	static final String LOGIN_URL = "https://www.shacknews.com/account/signin";
	static final String USER_AGENT = "shackbrowseAPI/1.1";
	
	static final String SN_USERNAME = "retarded talking dinosaur";
	static final String SN_PASSWORD = "halolol";
	
	private static final Logger logger = Logger.getLogger(LoginDownload.class.getName());
	
	public static String get (String url)
	{
		Key aliceKey = KeyFactory.createKey("Cookie", "Login");
		 
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity alice;
		 
		String cookiedata = null;
		try {
		    alice = datastore.get(aliceKey);
		 
		    cookiedata = (String) alice.getProperty("data");
		} catch (EntityNotFoundException e) {
		    // no cookie data
			loginAndUpdateCookie();
			
			try {
				alice = datastore.get(aliceKey);
			}
			catch (EntityNotFoundException f) {
				return "";
			}
		    cookiedata = (String) alice.getProperty("data");
		}
		
		
		    
		MyResponseHandler response_handler = new MyResponseHandler();
	    HttpGet get = new HttpGet(url);
	    
        get.setHeader("User-Agent", USER_AGENT);
        get.setHeader("Cookie", cookiedata);
        logger.warning("cookie:" + cookiedata);
        DefaultHttpClient client = new DefaultHttpClient(new GAEConnectionManager());
        String content = "";
		try {
			content = client.execute(get, response_handler);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (url.contains("chatty"))
		{
			if (content.contains(SN_USERNAME))
				logger.warning("SUCCESSFULLY LOGGED IN");
			else
				logger.warning("LOGIN FAILURE");
		}
        return content;

	}

	public static boolean loginAndUpdateCookie()
	{
		try
		{
			// login
			MyResponseHandler response_handler = new MyResponseHandler();
		    DefaultHttpClient client = new DefaultHttpClient(new GAEConnectionManager());
		    
		    // Create a local instance of cookie store
		    CookieStore cookieStore = new BasicCookieStore();
	
		    HttpPost post = new HttpPost(LOGIN_URL);
		    post.setHeader("User-Agent", USER_AGENT);
		    post.setHeader("X-Requested-With", "XMLHttpRequest");
		    
		    
		    List<NameValuePair> values = new ArrayList<NameValuePair>();
		    values.add(new BasicNameValuePair("get_fields[]", "result"));
		    values.add(new BasicNameValuePair("user-identifier", SN_USERNAME));
		    values.add(new BasicNameValuePair("supplied-pass", SN_PASSWORD));
		    values.add(new BasicNameValuePair("remember-login", "1"));
		    
		    UrlEncodedFormEntity e = new UrlEncodedFormEntity(values,"UTF-8");
		    post.setEntity(e);
		    
		    String content = client.execute(post, response_handler);
		    if (content.contains("{\"result\":{\"valid\":\"true\""))
		    {
		    	Entity alice = new Entity("Cookie", "Login");
		    	alice.setProperty("data", response_handler.cookie[0].getName() + "=" + response_handler.cookie[0].getValue() + ";");
		    	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		    	datastore.put(alice);
		    	return true;
		    }
		}
		catch (Exception e)
		{ return false; }
		return false;
	}
}